<?php

declare(strict_types=1);

namespace app\controller\api;


use app\controller\api\Base;
use app\util\WechatService;
use think\Exception;
use think\Response;

/**
 * 微信相关接口
 */
class Wechat extends Base
{

    /**
     * 获取openid
     */
    public function getOpenid(): Response
    {
        $param = $this->request->param();
        $code = $param['code'];
        //  $code = '0b3mxqGa1N0n9F0UfhHa1A0edR2mxqGK';
        if ($code == '') {
            return $this->buildFailed(400, 'code 不能为空');
        }
        $wechat = new WechatService;
        $result = $wechat->wechatXcx()->auth->session($code);
        return $this->buildSuccess(['result' => $result]);
    }


    /**
     * 微信支付回调
     */
    public function notify(): Response
    {
        $xml = file_get_contents('php://input');
        $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        //file_put_contents('logpayt.txt',var_export($result,true),FILE_APPEND);
        // $result = 		array (
        //     'appid' => 'wx89019db17c8bb3db',
        //     'bank_type' => 'OTHERS',
        //     'cash_fee' => '1',
        //     'cash_fee_type' => 'CNY',
        //     'contract_id' => '202308115703547348',
        //     'fee_type' => 'CNY',
        //     'is_subscribe' => 'N',
        //     'mch_id' => '1602951295',
        //     'nonce_str' => '1XX7lDug4byFTmS8',
        //     'openid' => 'og3p36CDc9fwXHKGOJv2Fet5eA-0',
        //     'out_trade_no' => 'DK2023081159938',
        //     'result_code' => 'SUCCESS',
        //     'return_code' => 'SUCCESS',
        //     'return_msg' => 'OK',
        //     'sign' => 'B619CA013F2B1669FA6AB7B933F9BD21',
        //     'sub_mch_id' => '1606429468',
        //     'time_end' => '20230811165726',
        //     'total_fee' => '1',
        //     'trade_state' => 'SUCCESS',
        //     'transaction_id' => '4200066284202308112575996911',
        // );
        $wechat = WechatService::notify($result);
        return $this->buildSuccess(['result' => $wechat]);
    }

    /**
     *  微信退款
     */
    // public function refund()
    // {
    //     // $param = $this->request->param();
    //     try {
    //         // $row = Db::table('ea_order')->where('orderno',$orderno)->where('status','0')->find();
    //         // if(!$row){
    //         //     throw new \Exception("该订单不存在");
    //         // }
    //         // $member = Db::table('ea_member')->where('id',$row['memberid'])->find();
    //         $transactionId = 'gxy2023041628932';
    //         $refundNumber = 'tuikuan' . time();
    //         $refundFee = 0.01;
    //         $totalFee = 0.01;
    //         $result = WechatService::refund($transactionId, $refundNumber, $totalFee, $refundFee);
    //         $this->fmap['data'] = $result;
    //     } catch (\Exception $e) {
    //         $e->getMessage();
    //         $code = 0;
    //     }
    //     return json($this->fmap);
    // }


    //获取手机号 2023/11/14
    public function getPhone()
    {
        $param = $this->request->param();
        $code = $param['code'];

        if ($code == '') {
            return $this->buildFailed(400, 'code 不能为空');
        }
        $wechat = new WechatService;
        $result = $wechat->getPhone($code);
        $result = json_decode($result, true);
        if ($result['errcode'] != '0') {
            throw new \Exception($result['errmsg']);
        }
        $data['phoneNumber'] = $result['phone_info']['phoneNumber'];
        $data['purePhoneNumber'] = $result['phone_info']['purePhoneNumber'];
        return $this->buildSuccess(['result' => $data]);
    }


    // public function generateQrcode($xcx_path=''){
    //     $param = $this->request->param();
    //     $xcx_path = $param['xcx_path'];
    //     $openid = $param['openid'];
    //     $memberid = $this->openidToMemberid($openid);
    //     $xcx_path = $xcx_path.'?memberid='.$memberid;
    //     $response = $this->wechatapp->app_code->get(
    //         $xcx_path,
    //         ['is_hyaline' => true]
    //     );
    //     $path = 'upload/qrcode';
    //     $filename = 'qrcode' . time() . '.png';
    //     if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
    //         $filename = $response->saveAs($path, $filename);
    //     }
    //     //小程序二维码名字
    //     $xcx_qrcode = $path . '/' . $filename;
    //     $this->fmap['data']['qrcode_url'] = $xcx_qrcode;
    //     return json($this->fmap);
    // }

    // public function testPay()
    // {
    //     $orderno = time();
    //     $body = '测试';
    //     $amount = 1;
    //     $openid = 'o3pF264epBxWquc1QqlgoI_QA-jU';
    //     $resutl =   WechatService::pay($orderno, $body, $amount, $openid);
    //     return json($resutl);
    // }
}
